from BGP import BasicUpdate
from Stat import PrefixGraph
from Lib import Util, StateDBHelper, UpdateDBHelper
import sys, datetime, string, exceptions, calendar, time, random, sets, os

# Check command line arg length and exit on something unexpected
if len(sys.argv) < 4:
    print 'Usage: %s YYYY-MM-DD YYYY-MM-DD prefixes' % sys.argv[0]
    sys.exit(1)

def get_dt(ymd, hms = (0, 0, 0)):
       return datetime.datetime(int(ymd[0]), int(ymd[1]), int(ymd[2]), hms[0], hms[1], hms[2])

def processPrefix(id, ip, mask):
    line_num = 0
    stateDBHelper.setPrefix(ip, mask)
    ppg = PrefixGraph.PrefixGraph(startDate, endDate, stateDBHelper)
    
    print 'Processing ip %s/%s' % (ip, mask)
        
    if not ppg.dataStartDate:
        logFile.write("Skipping prefix %s/%s, no new data\n" % (ip, mask))
        return
    
    updateDBHelper.loadUpdates(id, startDate, endDate)    
    updates = updateDBHelper.fetchUpdates()
    while updates:
        for update in updates:
            #updates order: time, type, peer_as, as_path
            utcTime = int(time.mktime(update[0].timetuple())) - time.altzone
            if update[1] == 'A':
                asPath = map(int, update[3].split(" "))
            else:
                asPath = None
            ppg.updateGraph(utcTime, update[1], update[2], asPath)
        updates = updateDBHelper.fetchUpdates()            

    ppg.writeStatsToDB(endDateSeconds)
    
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) #disables print buffering

startDate = get_dt(sys.argv[1].split('-'), (0, 0, 0))
endDate = get_dt(sys.argv[2].split('-'), (23, 59, 59))
startDateSeconds = time.mktime(startDate.timetuple()) - time.altzone
endDateSeconds = time.mktime(endDate.timetuple()) - time.altzone

updateDBHelper = UpdateDBHelper.UpdateDBHelper(sys.argv[4]) #hack
stateDBHelper = StateDBHelper.StateDBHelper(PrefixGraph.STAT_TYPES)

logFile = open('%s/%s.txt' % (Util.log_dir, datetime.datetime.now()), 'w')
logFile.write('%s\n' % sys.argv[0])

if sys.argv[3] == 'all':
    print "Loading ip list...",
    prefixList = updateDBHelper.getPrefixList()
    print "done"
    prefixSet = sets.Set()
    while (len(prefixSet) < 500):
        prefixSet.add(prefixList[random.randint(0, len(prefixList))])    
        
    for row in prefixSet: # should be idList
        processPrefix(row[0], row[1], row[2])
else:
    prefixes = sys.argv[3:]
    print "Processing %s prefixes:\n%s" % (len(prefixes), prefixes)    
    for prefix in prefixes:
        row = updateDBHelper.getMasterEntry(prefix)
        processPrefix(row[0], row[1], row[2])
    
print "\n\n*****************DONE**********************"